import puppeteer from "puppeteer";
import * as fs from "fs";
import * as mysql from "mysql2/promise";
import rivalList from "./blackList.js";
import tool from "./utils/tool.js";

const username = "登科小号";
const data = fs.readFileSync(`./cookie/${username}.json`, "utf8");
const cookie = JSON.parse(data);

let keyword = "";
keyword = process.argv.slice(2).join(" ") || "南京考研自习室";

const baseHref = "https://www.xiaohongshu.com";
let connection;

const dbConnect = async () => {
  connection = await mysql.createConnection({
    host: "127.0.0.1",
    user: "root",
    password: "wk051105",
    database: "sql_hongshu_electron",
  });
  console.log("数据库连接成功");

  // connection.end();
};

// 打开浏览器任务
const mainTask = async () => {
  dbConnect();

  // 启动浏览器
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
    args: ["--no-default-browser-check"],
    executablePath:'E:\\project\\hongshu_spider\\chrome-win\\chrome.exe',
  });
  const context = await browser.createBrowserContext();
  context.setCookie(...cookie);
  // console.log(cookie);

  const homeUrl = `${baseHref}/search_result?keyword=${keyword}&source=web_search_result_notes`;

  const page = await context.newPage();
  await page.goto(homeUrl);

  async function getList() {
    await page.waitForSelector(".note-item");
    const listItems = await page.$$eval(".note-item", (elements) => {
      return elements.map((item) => {
        const title = item.querySelector("a.title")?.textContent || "";
        const name = item.querySelector("span.name")?.textContent || "";
        const href = item.querySelector("a.mask")?.getAttribute("href") || "";
        return { title, href, name };
      });
    });

    // console.log(listItems);

    // 非黑名单中的同行发布的信息
    const newList = listItems
      .filter((item) => {
        // 标题 发布人包含黑名单中的同行
        return !rivalList.some(
          (keyword) =>
            item.name.includes(keyword) || item.title.includes(keyword)
        );
      })
      .filter((item) => {
        return item.href;
      });
    // 黑名单
    const blackList = listItems.filter((item) => {
      return rivalList.some(
        (keyword) => item.name.includes(keyword) || item.title.includes(keyword)
      );
    });
    // console.log(newList);
    // console.log(newList.length);
    // console.log(blackList);
    // console.log(blackList.length);

    return newList;
  }

  const openDetail = async (item) => {
    const url = baseHref + item.href;
    // console.log(item?.title);
    // console.log(item?.name);

    // 判断是否评论过
    const urlObj = new URL(url);
    const keyword = urlObj.pathname.replace("/search_result/", "");
    const sql = "SELECT * FROM spider where path like ?";
    const queryParams = [`%${keyword}%`];
    const [results] = await connection.query(sql, queryParams);
    // console.log(queryParams);
    // console.log(results);
    // console.log(results.length);
    // console.log(results.length > 0);

    const detailPage = await context.newPage();

    if (results.length > 0) {
      console.log(
        `标题为：${item?.title}的笔记已经评论过了，执行跳过 ${tool
          .dayjs()
          .format("MM/DD HH:mm:ss")}`
      );
      console.log(url);
    } else {
      console.log(
        `标题为：${item?.title}的笔记开始评论 ${tool
          .dayjs()
          .format("MM/DD HH:mm:ss")}`
      );
      console.log(url);

      await detailPage.goto(url);
      await detailPage.waitForSelector(".comments-el");

      // 发布
      await inputContent(detailPage);
      // 保存已评论的路径
      await saveCommentId(url);

      await tool.sleep(parseInt(Math.random() * 30) * 1000 + 30 * 1000);
    }
    console.log("");

    await tool.sleep(1000);
    detailPage.close();
  };

  // 输入内容
  const inputContent = async (page) => {
    // const article =
    //   "①吃、住、学一站式备考基地\n②寄宿备考+择校规划+督学+模考+答疑\n③单人间/双人间/三人间/四人间\n④自营食堂，一天33元\n⑤提供住宿宽带➕健身/游泳➕意外保险➕床上六件套";
    const articles = [
      "吃住学一体化 上岸退费",
      "寄宿备考就选南京登科",
      "同学你好，看看我们呐",
      `①自习室水电网全免
      ②宿舍区水和网全免
      ③自营食堂，一天33元
      ④吃、住、学一站式备考基地
      ⑤单人间/双人间/三人间/四人间
      ⑥寄宿备考+择校择专+督学+模考+答疑
      ⑦提供健身、游泳、意外保险、床上六件套`,
      "礼貌打扰,欢迎咨询",
    ];

    const content1 = await page.waitForSelector("div.content-edit");
    content1.click();

    return new Promise(async (resolve) => {
      await tool.sleep(1000);

      const content2 = await page.waitForSelector("p.content-input");
      // content2.type(article);

      await page.keyboard.sendCharacter(articles[parseInt(Math.random() * articles.length)]);
      // 评论@主号
      // await page.keyboard.press("@");
      // await tool.sleep(250);
      // await page.keyboard.sendCharacter("南京登科寄宿备考自习室");
      // const unionTarget = await page.waitForSelector("li.highlight");
      // unionTarget.click();

      // 评论 并 提交
      const sumbit = await page.waitForSelector("button.submit");
      await tool.sleep(500);
      sumbit.click();
      resolve(0);
    });
  };

  // 记录到库
  const saveCommentId = async (url) => {
    // 插入
    const sql =
      "INSERT INTO spider (id, path, keyword, username) VALUES (0, ?, ?,?)";
    const newUrl = url.replace("https://www.xiaohongshu.com/", "");
    const addarams = [newUrl, keyword, username];
    const [results] = await connection.query(sql, addarams);
    // console.log('INSERT ID:', results);
    console.log("已评论并记录");
  };

  let listIndex = 0;
  const runList = async () => {
    // 执行任务
    const list = await getList();

    for (const [i, item] of list.entries()) {
      await tool.sleep(1000);
      // console.log(i);
      // console.log(item);

      // 打开详情页
      await openDetail(item);
    }

    await tool.sleep(2000);

    // 列表滚动
    listIndex++;

    if (listIndex >= 6) {
      console.log("重置搜索");
      listIndex = 0;

      await page.goto(homeUrl);
      await tool.sleep(25 * 1000);
      runList();
    } else {
      console.log(`列表滚动到第 ${listIndex+1} 页`);
      await page.evaluate(async (listIndex) => {
        window.scrollTo({
          left: 0,
          top: listIndex * 3000,
          behavior: "smooth",
        });
      }, listIndex);

      await runList();
    }
  };
  runList();
  // https://juejin.cn/post/7047462936293408776#heading-12
};

mainTask();
